﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


using Semantics;
using Semantics.Base;
using System.Runtime.InteropServices;


namespace Semantics.Example.ParserExample
{
    
    public partial class ParserForm : Form
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetActiveWindow();

        SemanticNode correct = null;
        private int flag;
        public ParserForm(string Sentence,int flag)
        {
            InitializeComponent();
            this.textBoxInput.Text = Sentence;
            this.flag = flag;
        }

        private void SemanticsExampleForm_Load(object sender, EventArgs e)
        {
            if (this.DesignMode)
                return;
            try
            {
                
            }
            catch (Exception exp)
            {
                MessageBox.Show("Parsing Exception:" + exp.Message);
            }
        }
        SortedList<int, Semantics.Parse.AmbiguityResolver.LangNodeAmbiguities> ambiguitieslist;
        public SortedList<int, Semantics.Parse.AmbiguityResolver.CorrectNode> CorrectNodeList=new SortedList<int,Parse.AmbiguityResolver.CorrectNode> ();
        SortedList<int, string> leafNodelist;
        Semantics.Parse.AmbiguityResolver resolver;
 
        private void buttonParse_Click(object sender, EventArgs e)
        {
            try
            {
                string name = SearchName(this.textBoxInput.Text);
                string text = null;

                if (name != null)
                {
                    text = Clean(name, this.textBoxInput.Text.Trim());
                    Node[] words = NLP.Dictionary.GetWord(name);
                    if (words == null)
                        NLP.Dictionary.InsertWord(name, "[人名]");
                }

                else
                    text = this.textBoxInput.Text.Trim();
                ISemanticParser parser = (ISemanticParser)NLP.CreateSemanticParser();
                List<SemanticNode> semanticnodes = parser.SemanticParse(text);
                this.ResolveAmbiguity(semanticnodes);
            }
            catch (ParseAmbiguitiesException exp)
            {
                SortedList<int, Semantics.Parse.AmbiguityResolver.CorrectNode> CandidatesCorrectNodeList = new SortedList<int, Parse.AmbiguityResolver.CorrectNode>();
                resolver = new Semantics.Parse.AmbiguityResolver();
                if (exp.Candidates != null && exp.Candidates.Count > 0)
                {
                    //for (int CandidatesItem = 0; CandidatesItem < exp.Candidates.Count; CandidatesItem++)
                    //{
                    //    //说明分支的结果只有一个意思，没有歧异，则直接加入到CandidatesCorrectNodeList;
                    //    if (exp.Candidates[CandidatesItem].LanguageNodes.Count == 1)
                    //    {
                    //        resolver.AddLangNodeToCorrectNode(exp.Candidates[CandidatesItem].LanguageNodes[0], CandidatesCorrectNodeList);
                    //    }
                    //    else
                    //    {
                    //        //也说明没有歧异
                    //        if (exp.Candidates[CandidatesItem].LanguageNodes.Count <= exp.Candidates[CandidatesItem].SemanticNodes.Count)
                    //        {
                    //            resolver.AddLangNodeToCorrectNode(exp.Candidates[CandidatesItem].LanguageNodes[0], CorrectNodeList);
                    //        }
                    //        //有歧异，需要进行用户交互分析
                    //        else
                    //        { 
                    //        }
                    //    }
                    //}
                    ResolveAmbiguity(exp.Candidates[0]);
                        ResolveParseAmbiguitiesException(exp.Candidates[0]);
                }
            }
            catch (ParseFailureException exp)
            {
                if (exp.Candidates != null && exp.Candidates.Count > 0)
                {
                    ResolveParseAmbiguitiesException(exp.Candidates[0]);
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show("Parsing Exception:" + exp.ToString());
            }
        }

        void ResolveAmbiguity(SemanticPosition segment)
        {
            //从Segment中找出所有有效的SemanticNode
            List<SemanticNode> semanticnodes = new List<SemanticNode>();
            for (int i = 0; i < segment.LanguageNodes.Count; i++)
            {
                LangNode langnode = segment.LanguageNodes[i];
                for (int j = 0; j < langnode.SemanticNodes.Count; j++)
                {
                    if (langnode.SemanticNodes[j].IsValidNode())
                        semanticnodes.Add(langnode.SemanticNodes[j]);
                }
            }
            this.ResolveAmbiguity(semanticnodes);            
        }
        void ResolveAmbiguity(List<SemanticNode> semanticnodes)
        {
            this.langNodeControl1.Nodes.Clear();

            leafNodelist = new SortedList<int, string>();
            resolver = new Semantics.Parse.AmbiguityResolver();
            //Semantics.Parse.SemanticNodeToLattice extract = new Semantics.Parse.SemanticNodeToLattice();
            //List<LangNode> LangNodeList = extract.ExtractLangNode(semanticnodes);
            ambiguitieslist = resolver.Resolve(leafNodelist, semanticnodes);
            CorrectNodeList = resolver.InitialCorrectNode();

            foreach (KeyValuePair<int, Semantics.Parse.AmbiguityResolver.CorrectNode> item in CorrectNodeList)
            {
                CreatCorrectTree(item.Key);
                break;
            }
        }
        void ResolveParseAmbiguitiesException(SemanticPosition segment)
        {
            this.ResolveAmbiguity(segment.SemanticNodes);
        }
        public void CreatCorrectTree(int key)
        {
            Semantics.Parse.AmbiguityResolver.resultOfCount CountResult = new Semantics.Parse.AmbiguityResolver.resultOfCount();            
            int ParentKey=0;
            int ParentSN=0;
            int i;
            int ChildKey;
            LangNode tempLangNode;
            if (ambiguitieslist[key].Parents.Count == 1)
            {
                foreach (KeyValuePair<int, LangNode> item in ambiguitieslist[key].Parents)
                {
                    ParentSN = item.Key;
                }
                //找到了根节点
                if (string.Compare(ambiguitieslist[key].Parents[ParentSN].Value, this.textBoxInput.Text.Trim()) == 0)
                {
                    this.showResult(ambiguitieslist[key].Parents[ParentSN].SemanticNodes[0]);
                    //this.Show();
                }
                else
                {
                    //将该结点和其父节点以及该父节点的其他孩子几点都加入CorrectNodeList，并且这些结点的IsScanned=True
                    // CreatCorrectTree(ambiguitieslist[key].Parent)
                    foreach (KeyValuePair<int, LangNode> item in ambiguitieslist[key].Parents)
                    {
                        
                        ParentKey = resolver.findIndexInAmbiguitieslist(item.Value.Value);
                        CorrectNodeList = resolver.AddCorrectNode(ambiguitieslist[ParentKey], ParentKey, CorrectNodeList);
                        //CorrectNodeList[ParentKey].IsScanned = true;
                        for (i = 0; i < item.Value.Children.Count; i++)
                            {
                                tempLangNode = item.Value.Children[i];
                                ChildKey = resolver.findIndexInAmbiguitieslist(tempLangNode.Value);
                                CorrectNodeList = resolver.AddCorrectNode(ambiguitieslist[ChildKey], ChildKey, CorrectNodeList);
                                CorrectNodeList[ChildKey].IsScanned = true;
                            }
                        }

                    CreatCorrectTree(ParentKey);
                }
            }
            else
            {
                CountResult = resolver.AmbiguitiesParentAllInCorrectNode(key,ambiguitieslist,CorrectNodeList);
                //说明有分支，进行交互
                if (CountResult.count > 1)
                {
                    CorrectNodeList[key].IsScanned = true;
                    ShowInterfaceForm showInterface = new ShowInterfaceForm(this.textBoxInput.Text, key, leafNodelist, ambiguitieslist,CountResult, this);
                    showInterface.Show();
                    return;
                    
                }
                //尝试CorrectNodeList域中IsScanned=False的结点
                else
                {
                    int maxKey=0;
                    foreach (KeyValuePair<int, Semantics.Parse.AmbiguityResolver.CorrectNode> item in CorrectNodeList)
                    {
                        if (item.Key > maxKey)
                            maxKey = item.Key;
                    }
                    foreach(KeyValuePair<int,Semantics.Parse.AmbiguityResolver.CorrectNode> item in CorrectNodeList)
                    {
                        if (item.Value.IsScanned == false)
                        {
                            if ((key != maxKey && item.Key > key) || (key == maxKey && item.Key < key))
                            {
                                CreatCorrectTree(item.Key);
                                break;
                            }

                        }
                        else
                        {
                            //如果是CorrectNodeList的最后一个值的IsScanned=true,要进行新一轮的轮询，确保所有的IsScanned都是True;
                            if (item.Key == maxKey)
                            {
                                foreach (KeyValuePair<int, Semantics.Parse.AmbiguityResolver.CorrectNode> item2 in CorrectNodeList)
                                {
                                    if (item2.Value.IsScanned == false)
                                    {
                                        CreatCorrectTree(item2.Key);
                                        break;
                                    }
                                }
                            }
                        }
                    }                                        
                }
            } 
        }
      
        public string SearchName(string str)
        {
            string[] splitName;
            string name;
            splitName = str.Split('<');
            if (splitName.Length == 1)
                return null;
            splitName = splitName[1].Split('>');
            name = splitName[0];
            return name;
        }

        public string Clean(string name, string str)
        {
            string cleanStr;
            cleanStr = str.Replace("<","");
            cleanStr = cleanStr.Replace(">","");
            return cleanStr;
        }
        private void buttonShow_Click(object sender, EventArgs e)
        {
            try
            {
                NLP.ShowClassHierarchy();
            }
            catch (Exception exp)
            {
                MessageBox.Show("Parsing Exception:" + exp.Message);
            }
        }

        //显示结果
        public void showResult(SemanticNode semanticNode)
        {
            this.correct = semanticNode;
            this.langNodeControl1.Nodes.Clear();
            this.langNodeControl1.ShowSemanticNode(semanticNode, this.langNodeControl1.Nodes, 0);
        }
        //交互选择后删除无用结点
        public void deleteUslessNode(string key)
        { 
        }
        private void textBoxInput_TextChanged(object sender, EventArgs e)        {

        }

        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            
            XmlSemanticNode xmlnode = new XmlSemanticNode(this.correct);
            string xml = xmlnode.ToXml();
            dbSql sql = new dbSql();
            if (sql.AddSemanticTree(this.textBoxInput.Text, xml))
                MessageBox.Show("保存成功、成功添加到数据库！");
            else
                MessageBox.Show("保存失败、未添加到数据库！");
        }

        private void toolStripButtonResolveSemanticAmbiguities_Click(object sender, EventArgs e)
        {
            if (this.langNodeControl1.Nodes.Count != 1)
            {
                MessageBox.Show(this, "语言消歧未成功！");
                return;
            }
            try
            {
                LangNode root = ((SemanticNode)this.langNodeControl1.Nodes[0].Tag).LanguageNode;
                SemanticNodeResolveForm form = new SemanticNodeResolveForm(root);
                form.ShowDialog();
            }
            catch (Exception exp)
            {
                MessageBox.Show(this, exp.ToString());                    
            }
        }
    }
}
